import { Message } from "element-ui";

let gWebSocket = {
  websock: null,
  messageCallback: null,
  errorCallback: null,
  tryTime: null,
  websocketonmessage: function(e) {
    let res = "";
    try {
      if (e.data) {
        res = JSON.parse(e.data);
      }
    } catch (error) {
      res = "err";
    }
    this.messageCallback(res);
    return res;
  },
  /**
   * 发起websocket连接
   * @param {Object} agentData 需要向后台传递的参数数据
   */
  websocketSend: function(agentData) {
    // 加延迟是为了尽量让ws连接状态变为OPEN
    setTimeout(() => {
      // 添加状态判断，当为OPEN时，发送消息
      if (this.websock.readyState === this.websock.OPEN) {
        // websock.OPEN = 1
        // 发给后端的数据需要字符串化
        this.websock.send(JSON.stringify(agentData));
      }
      // console.log(this.websock.readyState);
      if (this.websock.readyState === this.websock.CLOSED) {
        // websock.CLOSED = 3
        console.log("websock.readyState=3", this.websock);
        this.errorCallback();
      }
    }, 500);
  },
  websocketclose: function(e) {
    // e.code === 1000  表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。
    // e.code !== 1000  表示非正常关闭。
    if (e && e.code !== 1000) {
      // Message.error('网络连接异常，正在重连')
      // this.errorCallback()
      // 异常重连
      if (this.tryTime < 10) {
        setTimeout(() => {
          this.websock = null;
          this.tryTime++;
          this.initWebSocket();
          // Message.error(` 第${this.tryTime}次重连`)
          Message.error(`连接失败 尝试重新连接`);
        }, 3 * 1000);
      } else {
        Message.error("重连失败！请稍后重试");
      }
    }
  },
  websocketOpen: function(e) {
    console.log("ws连接成功");
  },
  initWebSocket: function() {
    if (typeof WebSocket === "undefined") {
      Message.error("您的浏览器不支持WebSocket，无法获取数据");
      return false;
    }

    let moa_token = "";
    if (sessionStorage.getItem("userInfo")) {
      const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      moa_token = userInfo.moa_token.split(" ")[1];
    }
    let requstWsUrl = "";
    //目前用chatGPT代替了
    requstWsUrl = `wss://chatgpt.yl1001.com`;
    this.websock = new WebSocket(requstWsUrl);

    this.websock.onmessage = (e) => {
      this.websocketonmessage(e);
    };
    this.websock.onopen = () => {
      this.websocketOpen();
    };
    this.websock.onerror = () => {
      Message.error("ws连接异常，请稍候重试");
      this.errorCallback();
    };
    this.websock.onclose = (e) => {
      this.websocketclose(e);
    };
  },
  /**
   * 发起websocket请求函数
   * @param {string} url ws连接地址
   * @param {Object} agentData 传给后台的参数
   * @param {function} successCallback 接收到ws数据，对数据进行处理的回调函数
   * @param {function} errCallback ws连接错误的回调函数
   */
  sendWebsocket: function(agentData, successCallback, errCallback) {
    //   wsUrl = url
    this.initWebSocket();
    this.messageCallback = successCallback;
    this.errorCallback = errCallback;
    this.websocketSend(agentData);
  },

  /**
   * 关闭websocket函数
   */
  closeWebsocket: function() {
    if (this.websock) {
      this.websock.close(); // 关闭websocket
      this.websock.onclose(); // 关闭websocket
    }
  },
};

export default gWebSocket;
